﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;

namespace AutoFlatnessTest.Db
{
    public static class MesExtractionDb
    {

        public static MesExtraction Get(MesExtraction mes)
        {
            mes.ExtractionGroup = DateTime.Now.ToString("yyyyMMdd");

            using (var connection = DbHelp.GetSqlServerConn())
            {
                string sql = @"
select *
from t_CMCC_PlanenessExtraction
where ProjectName=@ProjectName and WorkOrder=@WorkOrder and ExtractionGroup=@ExtractionGroup";
                return connection.QueryFirstOrDefault<MesExtraction>(sql, mes);
            }
        }


        public static void AddUpdata(MesExtraction mes)
        {
            mes.ExtractionGroup = DateTime.Now.ToString("yyyyMMdd");
            mes.ExtractionCount = (int)((double)mes.CountAll * ((double)mes.ExtractionPer / 100.00));
            mes.CreatedTime = DateTime.Now;

            using (var connection = DbHelp.GetSqlServerConn())
            {
                string sql = @"
select *
from t_CMCC_PlanenessExtraction
where ProjectName=@ProjectName and WorkOrder=@WorkOrder and ExtractionGroup=@ExtractionGroup";
                var aaa = connection.QueryFirstOrDefault<MesExtraction>(sql, mes);

                if (aaa == null)
                {
                    connection.Insert(mes);
                }
                else
                {
                    aaa.CountAll = mes.CountAll;
                    aaa.ExtractionPer = mes.ExtractionPer;
                    aaa.ExtractionCount = mes.ExtractionCount;

                    connection.Update(aaa);
                }
            }
        }
    }
}
